import java.net.InetAddress;
import java.net.UnknownHostException;

public class Inet extends Object {

	private InetAddress _inetAddress;
	private int _bitMask;

	public Inet(InetAddress inetAddress, int bitMask) {
		super();

		if (inetAddress == null) {
			throw new IllegalArgumentException("Inet adresse is required.");
		} // if

		int maxBitMask = (inetAddress.getAddress().length * Byte.SIZE);

		if ((bitMask < 0) || (bitMask > maxBitMask)) {
			throw new IllegalArgumentException(String.format(
					"Bit mask can't be below 0 nor above %d for %s address.",
					maxBitMask, inetAddress.getHostAddress()));
		} // if

		_inetAddress = inetAddress;
		_bitMask = bitMask;
	} // Inet

	public Integer bitMask() {
		return _bitMask;
	} // bitMask

	public InetAddress inetAddress() {
		return _inetAddress;
	} // inetAddress

	
	public static Inet valueOf(byte[] addr) {
		Inet inet;
		
		try {
			inet = new Inet(InetAddress.getByAddress(addr), 0);
		} catch (UnknownHostException exception) {
			inet = null;
		}
		
		return inet; 
	}
	
	/* Se utiliza el metodo de factoria "valueOf" para transformar
       un campo "inet" de PostgreSQL a una clase Inet de Java */
	public static Inet valueOf(String string) {
		Inet inet;

		if (string != null) {
			int bitMask, index;
			InetAddress inetAddress;

			try {
				if ((index = string.indexOf('/')) > -1) {
					bitMask = Integer.parseInt(string.substring(index + 1));
					string = string.substring(0, index);
				} else {
					bitMask = 0;
				} // else

				inetAddress = InetAddress.getByName(string);

				inet = new Inet(inetAddress, bitMask);
			} catch (Exception exception) {
				throw new IllegalArgumentException(
						"Can't create valid inet address and mask.", exception);
			} // catch
		} else {
			inet = null;
		} // else

		return inet;
	} // valueOf

  /* El metodo "toString" devuelve una representacion valida para
     un campo "inet" nativo de PostgreSQL, partiendo de una clase Inet de Java */
	public String toString() {
		StringBuilder string;

		string = new StringBuilder();
		string.append(_inetAddress.getHostAddress());
		string.append('/');
		string.append(_bitMask);

		return string.toString();
	} // toString
} // Inet
